package edu.song.yeb.boot.controller;

import edu.song.yeb.boot.domain.Admin;
import edu.song.yeb.boot.pojo.AdminLogin;
import edu.song.yeb.boot.pojo.RespBean;
import edu.song.yeb.boot.service.AdminService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Objects;

@RestController
@Api("LoginController")
public class LoginController {

    @Resource
    private AdminService adminService;

    @PostMapping("/login")
    @ApiOperation(value = "登录后返回token")
    public RespBean login(@RequestBody AdminLogin admin, HttpServletRequest request) {
        System.err.println("login login login");
        return adminService.login(admin.getUsername(), admin.getPassword(), admin.getCode(), request);
    }

    @GetMapping("/logout")
    @ApiOperation(value = "用户注销")
    public RespBean logout() {
        //通过拦截器实现
        return RespBean.success("注销成功！");
    }

    @ApiOperation(value = "获取登录用户信息")
    @GetMapping("/admin/info")
    public Admin getAdminInfo(java.security.Principal principal) {
        if (Objects.isNull(principal)) {
            return null;
        }
        String username = principal.getName();
        Admin admin = this.adminService.findAdminByUsername(username);
        admin.setPassword(null);
        return admin;
    }
}
